<template>
  <el-row class="p-5 pt-0" @keyup.enter="getDictDataTable">

    <el-col v-if="showSearch">
      <el-form ref="searchForm" :inline="true" :model="search" class="demo-form-inline">
        <el-form-item label="字典名称" class="font-black">
          <el-select v-model="search.dictType" :disabled="loading" :size="store.layoutSize" style="width: 180px"
                     value-key="dictType"
                     placeholder="字典名称" @change="getDictDataTable">
            <el-option v-for="item in dictType.data" :label="item.dictName" :value="item.dictType"/>
          </el-select>
        </el-form-item>
        <el-form-item label="字典标签" class="font-black">
          <el-input v-model="search.dictLabel" :disabled="loading" :size="store.layoutSize" clearable
                    style="width: 180px"
                    placeholder="请输入字典标签"/>
        </el-form-item>
        <el-form-item label="状态" class="font-black">
          <el-select v-model="search.status" :disabled="loading" :size="store.layoutSize" clearable style="width: 100px"
                     placeholder="状态" @change="getDictDataTable">
            <el-option v-for="item in statusData.data" :label="item.dictLabel" :value="item.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :color="store.getTheme" :disabled="loading" :icon="Search" :size="store.layoutSize"
                     auto-insert-space type="primary" @click="getDictDataTable">查询
          </el-button>
          <el-button :color="store.getTheme" :disabled="loading" :icon="Refresh" :size="store.layoutSize"
                     auto-insert-space
                     plain @click="resetForm">重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <el-col class="flex justify-between">
      <div>
        <el-button :color="store.getTheme" :disabled="loading" :icon="Plus" :size="store.layoutSize" auto-insert-space
                   plain type="primary" @click="add">新增
        </el-button>
        <el-button :disabled="loading || tableDictData.data.length === 0" :icon="Download" :size="store.layoutSize"
                   auto-insert-space plain type="warning">
          导出
        </el-button>
        <el-button :disabled="loading" :size="store.layoutSize" auto-insert-space plain type="danger"
                   @click="route.push('/system/dict')">
          <template #icon>
            <el-icon>
              <CloseBold/>
            </el-icon>
          </template>
          关闭
        </el-button>
      </div>
      <div>
        <el-tooltip
            class="box-item"
            effect="dark"
            :content="showSearch?'隐藏搜索':'显示搜索'"
            placement="top"
        >
          <el-button :color="store.getTheme" :size="store.layoutSize" :icon="Search" @click="showSearch = !showSearch"
                     circle/>
        </el-tooltip>
        <el-tooltip
            class="box-item"
            effect="dark"
            content="刷新"
            placement="top"
        >
          <el-button :color="store.getTheme" :disabled="loading" :icon="Refresh" :size="store.layoutSize"
                     @click="getDictDataTable"
                     circle/>
        </el-tooltip>
      </div>
    </el-col>

    <el-col class="mt-2">
      <el-table :size="store.layoutSize" v-loading="loading" element-loading-text="正在努力加载中..."
                :data="tableDictData.data"
                row-key="dictCode" style="width: 100%" table-layout="auto"
                highlight-current-row empty-text="无数据">
        <el-table-column align="center" label="字典标签" prop="dictLabel"/>
        <el-table-column align="center" label="字典键值" prop="dictValue"/>
        <el-table-column align="center" label="字典排序" prop="dictSort"/>
        <el-table-column align="center" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">{{
                scope.row.status === '0' ? '正常' : '停用'
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注" width="180" prop="remark"/>
        <el-table-column align="center" label="创建时间" width="180">
          <template #default="scope">
            {{ moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="180">
          <template #default="scope">
            <el-link :size="store.layoutSize" :underline="false" class="text-xs" :style="{color: store.getTheme}"
                     @click="update(scope.row)">
              <el-icon>
                <EditPen/>
              </el-icon>
              修改
            </el-link>
            <el-link :size="store.layoutSize" :underline="false" class="text-xs ml-3" :style="{color: store.getTheme}"
                     @click="del(scope.row)">
              <el-icon>
                <Delete/>
              </el-icon>
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
    <el-col class="mt-3 flex justify-end">
      <el-pagination
          :small="store.layoutSize === 'small'"
          :default-current-page="search.pageNum"
          :currentPage="search.pageNum"
          :page-size='search.pageSize'
          :page-sizes="[10, 20, 50, 100]"
          :pager-count="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="search.total"
          @size-change="handlePageSiezeChange"
          @current-change="handleCurrentPageChange"
      />
    </el-col>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字典类型">
          <el-input v-model="form.dictType" :disabled="true"/>
        </el-form-item>
        <el-form-item label="数据标签" prop="dictLabel">
          <el-input v-model="form.dictLabel" placeholder="请输入数据标签"/>
        </el-form-item>
        <el-form-item label="数据键值" prop="dictValue">
          <el-input v-model="form.dictValue" placeholder="请输入数据键值"/>
        </el-form-item>
        <el-form-item label="样式属性" prop="cssClass">
          <el-input v-model="form.cssClass" placeholder="请输入样式属性"/>
        </el-form-item>
        <el-form-item label="显示排序" prop="dictSort">
          <el-input-number v-model="form.dictSort" controls-position="right" :min="0"/>
        </el-form-item>
        <el-form-item label="回显样式" prop="listClass">
          <el-select v-model="form.listClass">
            <el-option
                v-for="item in listClassOptions"
                :key="item.value"
                :label="item.label + '(' + item.value + ')'"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="item in statusData.data" :key="item.dictCode" :label="item.dictValue">{{
                item.dictLabel
              }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="flex justify-end">
        <el-button :loading="btnLoading" auto-insert-space type="primary" @click="submitForm(formRef)">
          提交
        </el-button>
        <el-button auto-insert-space @click="open = false">取消</el-button>
      </div>
    </el-dialog>

  </el-row>
</template>

<script setup lang="ts">
import {reactive, ref} from "vue";
import {useStore} from "@/store";
import {Delete, Download, EditPen, Plus, Refresh, Search} from "@element-plus/icons-vue"
import {getAllDictType} from "@/api/dictType";
import moment from 'moment'
import type {FormInstance, FormRules} from 'element-plus'
import {ElMessageBox, ElNotification} from "element-plus";
import {delDictData, getDictData, getDictDataByPage, saveDictData} from "@/api/dictData";
import {useRouter} from "vue-router";

//创建store
const store = useStore()

const route = useRouter()

//弹出层标题
const title = ref("")

//是否显示弹出层
const open = ref(false)

//显示搜索框
const showSearch = ref(true)

//默认禁用删除按钮
const delDisabled = ref(true)

//表格加载
const loading = ref(false)

//赋值状态信息
const statusData = reactive({
  data: []
})
getDictData({'dictType': 'sys_normal_disable'}).then(result => {
  statusData.data = result.data.data
})

//赋值所有字典类型
const dictType = reactive({
  data: []
})
getAllDictType().then(result => {
  dictType.data = result.data.data
})

const searchForm = ref<FormInstance>()
const formRef = ref<FormInstance>()

//新增、修改表单数据
const form = reactive({
  dictCode: null,
  dictType: null,
  dictLabel: null,
  dictValue: null,
  cssClass: null,
  dictSort: null,
  listClass: null,
  status: '0',
  remark: null,
  createBy: null,
  updateBy: null
})

//清除
function clearForm() {
  form.dictCode = null
  form.dictType = null
  form.dictLabel = null
  form.dictValue = null
  form.cssClass = null
  form.dictSort = null
  form.listClass = null
  form.status = '0'
  form.remark = null
  form.createBy = null
  form.updateBy = null
}

//新增字典类型事件
function add() {
  clearForm()
  form.dictType = search.dictType
  form.createBy = store.getUser.userName
  title.value = '添加字典数据'
  open.value = true
}

//修改字典类型事件
function update(val: any) {
  clearForm()
  form.dictType = search.dictType
  form.dictCode = val.dictCode
  form.dictLabel = val.dictLabel
  form.dictValue = val.dictValue
  form.cssClass = val.cssClass
  form.dictSort = val.dictSort
  form.listClass = val.listClass
  form.status = val.status
  form.remark = val.remark
  form.updateBy = store.getUser.userName
  title.value = '修改字典数据'
  open.value = true
}

//删除方法
function del(val) {
  ElMessageBox.confirm('您确定要删除字典编码为<' + val.dictCode + '>的数据项吗？', '警告', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    delDictData({dictCode: val.dictCode}).then(result => {
      if (result.data.code === 200) {
        ElNotification({
          message: result.data.msg,
          type: 'success'
        })
      }
      getDictDataTable()
    })
  })
}

const btnLoading = ref(false)

//提交新增、修改表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      btnLoading.value = true
      saveDictData(form).then(result => {
        if (result.data.code === 200) {
          ElNotification({
            message: result.data.msg,
            type: 'success'
          })
          open.value = false
        }
        getDictDataTable()
        btnLoading.value = false
      })
    }
  })
}

//重置表单
function resetForm() {
  search.dictLabel = null
  search.status = null
  getDictDataTable()
}

//查询表单数据
const search = reactive({
  dictType: null,
  dictLabel: null,
  status: null,
  pageNum: 1,
  pageSize: 10,
  total: 0,
})

search.dictType = route.currentRoute.value.params.dictType

//分页控制
function handleCurrentPageChange(val) {
  search.pageNum = val
  //获取数据
  getDictDataTable()
}

//页大小控制
function handlePageSiezeChange(val) {
  search.pageSize = val
  //获取数据
  getDictDataTable()
}

//赋值获取到的数据
const tableDictData = reactive({
  data: []
})
getDictDataTable()

function getDictDataTable() {
  loading.value = true
  getDictDataByPage(search).then(result => {
    search.total = result.data.data.total
    tableDictData.data = result.data.data.list
    loading.value = false
  })
}

//表单验证
const rules = reactive<FormRules>({
  dictLabel: [
    {required: true, message: "数据标签不能为空", trigger: "blur"}
  ],
  dictValue: [
    {required: true, message: "数据键值不能为空", trigger: "blur"}
  ],
  dictSort: [
    {required: true, message: "数据顺序不能为空", trigger: "blur"}
  ]
})

const listClassOptions = reactive([
  {
    value: "default",
    label: "默认"
  },
  {
    value: "primary",
    label: "主要"
  },
  {
    value: "success",
    label: "成功"
  },
  {
    value: "info",
    label: "信息"
  },
  {
    value: "warning",
    label: "警告"
  },
  {
    value: "danger",
    label: "危险"
  }
])
</script>

<style scoped>

</style>
